import requests
import json

def search_code(query, token):
    url = "https://api.github.com/search/code"
    headers = {
        "Accept": "application/vnd.github+json",
        "Authorization": f"Bearer {token}",
        "X-GitHub-Api-Version": "2022-11-28"
    }
    params = {
        "q": query
    }
    response = requests.get(url, headers=headers, params=params)
    if response.status_code == 200:
        return response.json()
    else:
        print(f"Error: {response.status_code}")
        return None

def github_search_test():
    
    # 示例用法
    query = "addClass in:file language:js repo:jquery/jquery"
    token = "YOUR_PERSONAL_ACCESS_TOKEN"
    result = search_code(query, token)
    if result:
        print(result)
    
    

def check_repo_exists_via_api(owner, repo):
    url = f"https://gitee.com/api/v5/repos/{owner}/{repo}"
    token = "b7670d05fd499f29e4048d39bc7e5a70"
    headers = {
        "Accept": "application/vnd.github+json",
        "Authorization": f"Bearer {token}",
        "X-GitHub-Api-Version": "2022-11-28"
    }
     
    response = requests.get(url)
    if response.status_code == 200:
        ret = json.loads(response.text)
        name = ret.get("name","")
        git_url = ret.get("html_url","")
        return True,name,git_url
    elif response.status_code == 404:
        return False,"",""
    else:
        print(f"Unexpected status code: {response.status_code}")
        return None,"",""

def gitee_search_test():
    # 示例用法
    owner = "src-openeuler"
    repo = "coreutils"
    ret,name,url = check_repo_exists_via_api(owner, repo)
    if ret:
        print(f"The repository {owner}/{repo} exists.")
    else:
        print(f"The repository {owner}/{repo} does not exist.")

def  gitee_search_pkg_name(repo ):
    owner = "src-openeuler"
    ret,name,url = check_repo_exists_via_api(owner, repo)
    if ret:
        print(f"The repository {owner}/{repo} exists.")
    else:
        print(f"The repository {owner}/{repo} does not exist.")

import subprocess

def check_repo_exists(repo_url):
    try:
        # 调用 git ls-remote 命令
        result = subprocess.run(
            ["git", "ls-remote", repo_url],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        
        # 检查返回码
        if result.returncode == 0:
            # 如果返回码为 0，说明仓库存在
            return True
        else:
            # 如果返回码不为 0，说明仓库不存在或无法访问
            print(f"Error: {result.stderr.strip()}")
            return False
    except Exception as e:
        print(f"An error occurred: {e}")
        return False

def read_csv():
    import pandas as pd
    import time
    import random
    
    third_pkg_unique = "match_third_pkg_unique.csv"
    third_pkgs = pd.read_csv(third_pkg_unique)
    
    # 初始化匹配结果列

    third_pkgs['git_pkg_name'] = ''  # 
    third_pkgs['git_url'] = ''  # 
    
    # 遍历第三方包
    for index, row in third_pkgs.iterrows():
        match = row['match']
        pkg_name = row['picked_package']
        if match == "rpm":
            query_pkg_name = pkg_name
        elif match == "python":
            query_pkg_name  =  "python-" + pkg_name
        elif match == "python3":
            query_pkg_name  =  "python3-" + pkg_name
        elif  match == "python-":
            query_pkg_name  =  pkg_name.replace("python-", "")
        else:
            query_pkg_name = pkg_name
        
        url = f"https://jhaiq:b7670d05fd499f29e4048d39bc7e5a70@gitee.com/src-openeuler/{query_pkg_name}.git"

        ret = check_repo_exists(url)
        # owner = "src-openeuler"
        # ret,name,url = check_repo_exists_via_api(owner, pkg_name)
        if ret:
            third_pkgs.at[index, 'git_pkg_name']= query_pkg_name
            third_pkgs.at[index, 'git_url'] = url
            print(f"find pkt:{query_pkg_name}") 
        else:
            third_pkgs.at[index, 'git_pkg_name']= ""
            third_pkgs.at[index, 'git_url'] = ""

        # if index >5:
        #     break
        
        time.sleep(random.randint(1,3))
    
    # 保存结果到新的 CSV 文件
    third_pkgs.to_csv("match_third_pkg_unique_gitee.csv", index=False)
    print("匹配结果已保存到 match_third_pkg_unique_gitee.csv")

if __name__ == "__main__":
    read_csv()
    pass